package com.cfks.webviewdriver;

import android.webkit.ValueCallback;
import com.cfks.webviewdriver.error.ElementNotFound;
import java.util.concurrent.CountDownLatch;

public class Element {
    private WebviewDriver wvd;
    private String toget = "";
	private CountDownLatch latch = null;
	private ElementNotFound exception = null;
    public Element(final String name, int by, WebviewDriver wvd, int cn) throws ElementNotFound {
        this.wvd = wvd;
        if (by == By.by_id) {
            this.toget = "document.getElementById('" + name + "')";
			latch = new CountDownLatch(1);
			wvd.getWebView().evaluateJavascript("javascript:(function() { let element = " + this.toget + "; return (elements != null || elements != undefined); })()", new ValueCallback<String>() {
					@Override
					public void onReceiveValue(String value) {
						boolean isElementExists = Boolean.parseBoolean(value);
						if (!isElementExists) {
							exception = new ElementNotFound("getElementById " + name + " Not Found");
						}
						latch.countDown();
					}
				});
        } else if (by == By.by_classname) {
            this.toget = "document.getElementsByClassName('" + name + "')[" + cn + "]";
			latch = new CountDownLatch(1);
			wvd.getWebView().evaluateJavascript("javascript:(function() { let elements = " + this.toget + "; return (elements != null || elements != undefined); })()", new ValueCallback<String>() {
					@Override
					public void onReceiveValue(String value) {
						boolean isElementExists = Boolean.parseBoolean(value);
						if (!isElementExists) {
							exception = new ElementNotFound("getElementsByClassName " + name + " Not Found");
						}
						latch.countDown();
					}
				});
        }	
		try {
			latch.await();
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
		if (exception != null) {
			throw exception;
		}
    }
    public void input(String text) {

    }
}
